/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-08-08
 * Time: 22:11
 */

//链表的回文
public class Exercise2 {
    static class ListNode{
        public ListNode next = null;
        public int val;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public boolean isPail (ListNode head) {
        // write code here
        if(head == null) {
            return true;
        }
        //找中间节点
        ListNode fast = head;
        ListNode slow = head;

        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

        //逆置,slow后面的节点
        ListNode cur = slow.next;
        while(cur != null) {
            ListNode curN = cur.next;
            cur.next = slow;
            slow = cur;
            cur = curN;
        }

        //找回文，head往后，slow往后走直到相遇
        while(head != slow) {
            head = head.next;
            slow = slow.next;

            //偶数情况下head的下一个节点是slow节点，并且两个节点的val相等。这个时候就要直接返回ture

            if(head.val != slow.val) {
                return false;
            }

            //到这里head.val == slow.val
            if(head.next == slow) {
                return true;
            }
        }
        return true;
    }
}
